/*
 * @Author: your name
 * @Date: 2022-01-04 18:40:58
 * @LastEditTime: 2022-01-20 13:17:42
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \fd-industry-zhangjiang-company-terminal\src\utils\fetch.js
 */
import axios from 'axios';
import { Spin, Message } from 'view-design';
// eslint-disable-next-line import/no-cycle
import store from '@/store';
// import router from '@/router';
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 60000
});
// 弹窗防抖
/* eslint-disable */
function debounce(fn, wait) {
  let timerId = null;
  let flag = true;
  return function () {
    // clearTimeout(timerId);
    if (flag) {
      fn.apply(this, arguments);
      flag = false;
      timerId = setTimeout(() => {
        flag = true;
      }, wait);
    }
  };
}
const authError = debounce(message => {
  Message.error({
    content: message,
    duration: 3
  })
}, 1000);
/* eslint-disable */
// request拦截器
service.interceptors.request.use(
  config => {
    config.headers = {
      'Content-Type': 'application/json',
      'Authorization': localStorage.getItem('ACCESS_TOKEN'),
      'System':1
    };
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    const xhr = response.data;
    const { code } = xhr;
    let thisReturn = '';
    if (code === 200) {
      Spin.hide();
      thisReturn = Promise.resolve(xhr);
    } else if (code === 403 || code === 401) {
      authError('未登录')
      window.localStorage.removeItem("ACCESS_TOKEN"); // 清除数据
      window.localStorage.removeItem("MENU_LIST"); // 清除用户信息
      window.localStorage.removeItem("USER_INFO"); // 清除用户信息
      window.localStorage.removeItem("ROlE_LIST"); // 清除路由权限
      // router.push('/')
      store.commit("LoginStatus", false);
      store.commit("loginPop", true);
      thisReturn = Promise.reject(xhr);
    } else {
      Spin.hide();
      if(xhr.message==='登录过期请重新登录！'){
        window.localStorage.clear();
        store.commit("LoginStatus", false);
        store.commit("loginPop", true);
      }
      authError(xhr.message)
      // Message.error({ content: xhr.message ? xhr.message : xhr.msg, duration: 2.5 });
      thisReturn = Promise.reject(xhr);
    }
    return thisReturn;
  },
  error => {
    Message.error('服务器异常，建议稍后重试');
    return Promise.reject(error);
  }
);

const fetch = (method, url, data) => {
  let thisReturnData = '';
  if (method === 'post') {
    thisReturnData = service.post(url, { ...data });
  } else if (method === 'get') {
    thisReturnData = service.get(url, {
      params: data
    });
  } else if (method === 'put') {
    thisReturnData = service.put(url, { ...data });
  } else if (method === 'delete') {
    thisReturnData = service.delete(url, {
      params: data
    });
  }
  return thisReturnData;
};

export default fetch;
